package cn.jtool.dig.common.model;


import cn.jtool.dig.common.netty.supports.ByteBuffer;
import cn.jtool.dig.common.netty.supports.PacketProcessing;
import cn.jtool.dig.common.netty.supports.Constants;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Objects;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Packet {

    private Byte begin;
    private PacketHeader header;
    private PacketBody body;
    private Byte check;
    private Byte end;
    public Packet(byte[] bytes) {
        ByteBuffer buffer = new ByteBuffer(bytes);
        this.begin = (byte) buffer.readByte();
        byte[] headerBytes = buffer.readBytes(7);
        this.header = new PacketHeader(headerBytes);
        byte[] bodyBytes = buffer.readBytes(bytes.length - 1 - 7 - 1 - 1);
        this.body = new PacketBody(bodyBytes);
        this.check = (byte) buffer.readByte();
        this.end = (byte) buffer.readByte();
    }

    public byte[] encoder(){
        ByteBuffer buffer = new ByteBuffer();
        buffer.write(header.toBytes());
        if(Objects.nonNull(body)) {
            buffer.write(body.getBytes());
        }
        buffer.writeByte(PacketProcessing.checkPackage(buffer.readAll()));
        byte[] escape = PacketProcessing.escape(buffer.readAll(), Constants.AGENT_ESCAPE, Constants.AGENT_TO_ESCAPE);

        ByteBuffer finalBytes = new ByteBuffer();
        finalBytes.writeByte(0x5B);
        finalBytes.write(escape);
        finalBytes.writeByte(0x5D);
        return finalBytes.readAll();
    }
}
